import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 通过meta.perm判断是否与当前用户权限匹配
 * @param perms 登录用户的权限
 * @param route 路由对象
 */
function hasPermission(perms, route) {
    //如果没有声明meta或者meta.perm，都视为可以公共访问的路由
    if (!route.meta || !route.meta.perm) {
        return true;
    }
    if(perms.some(p=>p=="*")) {
       return true;
    }
    return perms.some(p=>p==route.meta.perm);
}


/**
 * 递归过滤异步路由表，返回符合用户权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, perms) {
    const accessedRouters = routes.filter(route => {
        if (hasPermission(perms, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, perms)
            }
            return true
        }
        return false
    });
    return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
              //定义用户路由
              let accessedRouters;
              //权限字符数组
              let perms = data.perms;
              //包含所有权限
              if(perms.some(p=>p=="*")) {
                  accessedRouters = asyncRouterMap
              } else {
                  accessedRouters = filterAsyncRouter(asyncRouterMap, perms)
              }
              commit('SET_ROUTERS', accessedRouters)
              resolve()
          })
    }
  }
}
export default permission
